var retainProjectStore = null;
var retainPremisesStore = null;
var retainBuildingStore = null;
var retainUnitStore = null;
var retainRoomStore = null;

Ext.define('component.marketing.retainPanel', {
	extend : 'Ext.form.Panel',
	initComponent:function(){
		
		//项目
		retainProjectStore = new Ext.data.Store({
	        singleton:true,
	        autoDestroy:true,
	        fields: ["id", "projectName"],
	        proxy:{
	            type:'ajax',
	            url:contextPath+'/estate/project/findProjectList?resourcesCode=menu_0003_0001',
	            reader:{
                   type: 'json', 
                   root: 'root'  //数据
              }
	        } ,
	        autoLoad: false
		});
		retainProjectStore.load({
			callback:function(records, options, success){
				var count = retainProjectStore.getCount();
				if(count>0){
					var id = retainProjectStore.getAt(0).get("id");
					Ext.getCmp('retainProjectStore').setValue(id)
				}
				if(Ext.Array.contains(idata,"marketing:list:all")){
					var data = {"projectName": "全部", "id": '-1'};
					var rs = Ext.create(data);
					retainProjectStore.insert(count+1, rs);
				}
			}
		});
		//组团
		retainPremisesStore = new Ext.data.Store({
	        singleton:true,
	        autoDestroy:true,
	        fields: ["id", "groupName"],
	        proxy:{
	   			type:'ajax',
	            url:contextPath+'/estate/projectPremises/findPremisesList',
	            reader:{
                   type: 'json', 
                   root: 'root'  //数据
              	}
	        } ,
	        autoLoad: false
		});
		
		retainPremisesStore.on("beforeload", function(){
			retainPremisesStore.removeAll();
			retainBuildingStore.removeAll();
			retainUnitStore.removeAll();
			retainRoomStore.removeAll();
			Ext.getCmp("retainPremisesStore").setValue("");
			Ext.getCmp("retainBuildingStore").setValue("")
			Ext.getCmp("retainUnitStore").setValue("")
			Ext.getCmp("retainRoomStore").setValue("")
			var projectId = Ext.getCmp("retainProjectStore").getValue();
			if("-1" == projectId){
				projectId = "";
			}
			retainPremisesStore.proxy.extraParams.projectId = projectId;
		});
		//楼栋
		retainBuildingStore = new Ext.data.Store({
	        singleton:true,
	        autoDestroy:true,
	        fields: ["id", "buildingName"],
	        proxy:{
	   			type:'ajax',
	            url:contextPath+'/estate/projectBuilding/findBuildingList',
	            reader:{
                   type: 'json', 
                   root: 'root'  //数据
              	}
	        } ,
	        autoLoad: false
		});
		retainBuildingStore.on("beforeload", function(){
			retainBuildingStore.removeAll();
			retainUnitStore.removeAll();
			retainRoomStore.removeAll();
			Ext.getCmp("retainBuildingStore").setValue("")
			Ext.getCmp("retainUnitStore").setValue("")
			Ext.getCmp("retainRoomStore").setValue("")
			var projectId = Ext.getCmp("retainProjectStore").getValue();
			if("-1" == projectId){
				projectId = "";
			}
			var premisesId = Ext.getCmp("retainPremisesStore").getValue();
			retainBuildingStore.proxy.extraParams.projectId = projectId;
			retainBuildingStore.proxy.extraParams.premisesId = premisesId;
		});
		//单元
		retainUnitStore = new Ext.data.Store({
	        singleton:true,
	        autoDestroy:true,
	        fields: ["id", "unitName"],
	        proxy:{
	   			type:'ajax',
	            url:contextPath+'/estate/projectUnit/findUnitList',
	            reader:{
                   type: 'json', 
                   root: 'root'  //数据
              	}
	        } ,
	        autoLoad: false
		});
		retainUnitStore.on("beforeload", function(){
			retainUnitStore.removeAll();
			retainRoomStore.removeAll();
			Ext.getCmp("retainUnitStore").setValue("")
			Ext.getCmp("retainRoomStore").setValue("")
			var projectId = Ext.getCmp("retainProjectStore").getValue();
			if("-1" == projectId){
				projectId = "";
			}
			var premisesId = Ext.getCmp("retainPremisesStore").getValue();
			var buildingId = Ext.getCmp("retainBuildingStore").getValue();
			retainUnitStore.proxy.extraParams.projectId = projectId;
			retainUnitStore.proxy.extraParams.premisesId = premisesId;
			retainUnitStore.proxy.extraParams.buildingId = buildingId;
		});
		//房间
		retainRoomStore = new Ext.data.Store({
	        singleton:true,
	        autoDestroy:true,
	        fields: ["id", "roomName"],
	        proxy:{
	   			type:'ajax',
	            url:contextPath+'/estate/projectRoom/findRoomList',
	            reader:{
                   type: 'json', 
                   root: 'root'  //数据
              	}
	        } ,
	        autoLoad: false
		});
		retainRoomStore.on("beforeload", function(){
			retainRoomStore.removeAll();
			Ext.getCmp("retainRoomStore").setValue("")
			var projectId = Ext.getCmp("retainProjectStore").getValue();
			if("-1" == projectId){
				projectId = "";
			}
			var premisesId = Ext.getCmp("retainPremisesStore").getValue();
			var buildingId = Ext.getCmp("retainBuildingStore").getValue();
			var unitId = Ext.getCmp("retainUnitStore").getValue();
			retainRoomStore.proxy.extraParams.projectId = projectId;
			retainRoomStore.proxy.extraParams.premisesId = premisesId;
			retainRoomStore.proxy.extraParams.buildingId = buildingId;
			retainRoomStore.proxy.extraParams.unitId = unitId;
		});
		
		var formrp = Ext.create("Ext.form.Panel", {
			minHeight:60,
		    title: "查询条件",
		    collapsible: true,  //可折叠
		    autoScroll: false,   //自动创建滚动条
		    defaultType: 'textfield',
		    defaults: {
		    	 anchor: '100%'
		    },
		    fieldDefaults: {
		        margin: 2,
		        labelWidth: 80,
		        labelAlign: "right",
		        margin: "5 0 0 0"
		    },
		    items: [
				{
				    xtype: "container",
				    layout: "hbox",
				    items: [
						{  
				            xtype:'combobox',
				            id:'retainProjectStore',
				            name: "projectId",
				            store: retainProjectStore,
				            valueField: "id",  
				            displayField: "projectName",
				            fieldLabel:'所属项目',
				            queryMode:'local',
				            typeAhead: true,
				            editable: false,
				            listeners:{
				            	'change':function(value){
				            		//加载组团数据
				            		if(value.lastValue && value.lastValue != "-1"){
				            			retainPremisesStore.load({
				            				callback: function(records, operation, success){
				            					//若无组团数据，加载楼栋
				            					var recordLen = records.length;
				            					if(recordLen == 0){
				            						retainBuildingStore.load();
				            					}
				            				}
				            			});
				            		}else{
				            			retainPremisesStore.removeAll();
				            			retainBuildingStore.removeAll();
				            			retainUnitStore.removeAll();
				            			retainRoomStore.removeAll();
				            			Ext.getCmp("retainPremisesStore").setValue("");
				            			Ext.getCmp("retainBuildingStore").setValue("")
				            			Ext.getCmp("retainUnitStore").setValue("")
				            			Ext.getCmp("retainRoomStore").setValue("")
				            		}
				            	}
				            }
				        },
						{  
				            xtype:'combobox',
				            id:'retainPremisesStore',
				            name: "premisesId",
				            store: retainPremisesStore,
				            valueField: "id",  
				            displayField: "groupName",
				            queryMode:'local',
				            typeAhead: true,
				            editable: false,
				            listeners:{
				            	'change':function(value){
				            		//加载楼栋
				            		//若无楼栋数据，加载单元
				            		if(value.lastValue && value.lastValue != "-1"){
				            			retainBuildingStore.load({
				            				callback: function(records, operation, success){
				            					//若无组团数据，加载楼栋
				            					var recordLen = records.length;
				            					if(recordLen == 0){
				            						retainUnitStore.load();
				            					}
				            				}
				            			});
				            		}
				            	}
				            }
				        },
						{  
				            xtype:'combobox',
				            id:'retainBuildingStore',
				            name: "buildingId",
				            store: retainBuildingStore,
				            valueField: "id",  
				            displayField: "buildingName",
				            queryMode:'local',
				            typeAhead: true,
				            editable: false,
				            listeners:{
				            	'change':function(value){
				            		//加载单元
				            		//若无单元数据，加载房间
				            		if(value.lastValue && value.lastValue != "-1"){
				            			retainUnitStore.load({
				            				callback: function(records, operation, success){
				            					//若无组团数据，加载楼栋
				            					var recordLen = records.length;
				            					if(recordLen == 0){
				            						retainRoomStore.load();
				            					}
				            				}
				            			});
				            		}
				            	}
				            }
				        },
						{  
				            xtype:'combobox',
				            id:'retainUnitStore',
				            name: "unitId",
				            store: retainUnitStore,
				            valueField: "id",  
				            displayField: "unitName",
				            queryMode:'local',
				            typeAhead: true,
				            editable: false,
				            listeners:{
				            	'change':function(value){
				            		//加载房间
				            		if(value.lastValue && value.lastValue != "-1"){
				            			retainRoomStore.load();
				            		}
				            	}
				            }
				        },
						{  
				            xtype:'combobox',
				            id:'retainRoomStore',
				            name: "roomId",
				            store: retainRoomStore,
				            valueField: "id",  
				            displayField: "roomName",
				            queryMode:'local',
				            typeAhead: true,
				            editable: false
				        }
					]
				},{
		        	xtype: "container",
		            layout: "hbox",
		            items: [
						{xtype:"textfield", name:"resourcesCode", value: resourcesCode, hidden: true},
						{xtype:"textfield", name:"resourcesName", value: "resName_pin_list", hidden: true},
		                { xtype: "datefield", name: "retainDateBefore",fieldLabel: "保留开始日期",format:'Y-m-d'},
		                { xtype: "datefield", name: "retainDateAfter", fieldLabel: "保留结束日期",format:'Y-m-d'}
		            ]
		        },{
		        	xtype: "container",
		            layout: "hbox",
		            items: [
			                { xtype: "datefield", name: "startValidityBefore",fieldLabel: "保留有效开始日期",format:'Y-m-d'},
			                { xtype: "datefield", name: "endValidityAfter", fieldLabel: "保留有效结束日期",format:'Y-m-d'}
		            ]
		        },{
		        	xtype: "container",
		            layout: "hbox",
		            items: [
			                { 
								xtype: "checkboxgroup",
				            	id:"busStatuRp",
				            	fieldLabel: "业务状态",
				            	name :"m_businessStatus",
				            	width: 300,
				            	items:[{
					            		boxLabel:'保留',
					            		inputValue:'0'
					            	},{
					            		boxLabel:'解除保留',
					            		inputValue:'1'
					            	}
				                 ]
			            	}
		            ]
		        }
		        ],
		    buttons: [
	  	        { xtype: "button", text: "查询", 
	  	        	handler:function(){
	  	        		//获取通过checkboxgroup定义的checkbox值
	  	        		//业务状态
	  	        		var busStatusValue = Ext.getCmp('busStatuRp').getChecked();
	  	        		var busStatus="";
	  	        		Ext.Array.each(busStatusValue, function(item){
	  	        			busStatus += item.inputValue+',' ;
	  	        		});
	  	        		gridStorerp.getProxy().extraParams.m_businessStatus = busStatus;
	  	        		gridStorerp.load();
	  	        		var pagingTool=Ext.getCmp("pagingToolb");
	  	        		pagingTool.moveFirst();//跳至第一页
	  	        	}  
	  	        },
	  	        { xtype: "button", text: "清空",handler:function(){
	  	        		formrp.getForm().reset();
	  	        	}
	  	        },
	  	        {xtype: "button", text: "导出",hidden:retainDataExport,handler:function(){
	  	        	var count = gridrp.getStore().getCount();
	  	        	if(count<=0){
	  	        		 Ext.MessageBox.alert("系统提示","没有可导出的数据"); 
	  	        	}else{
	  	        		var busStatusValue = Ext.getCmp('busStatuRp').getChecked();
	  	        		var busStatus="";
	  	        		Ext.Array.each(busStatusValue, function(item){
	  	        			busStatus += item.inputValue+',' ;
	  	        		});
	  	        		gridStorerp.getProxy().extraParams.m_businessStatus = busStatus;
	  	        		var value = encodeURI(encodeURI(JSON.stringify(gridStorerp.getProxy().extraParams),"utf-8"));
	  	        		location.href=jypath+'/marketing/retain/retainExport?value='+value;
	  	        	}
	  	        	
		  	     }	
	  	        }
	  	    ]    
	});
	
	var gridStorerp = Ext.create('Ext.data.Store', {
        fields: ["id","retainDate","customerName", "combinedName"
                 , "houseTypeName","totalPrice","startValidity"
                 ,"endValidity","userName","retainType","roomId"],
        pageSize: 10,  //页容量5条数据
        //是否在服务端排序 （true的话，在客户端就不能排序）
        remoteSort: false,
        proxy: {
            type: 'ajax',
            url: jypath+'/marketing/retain/list',
            actionMethods: { read: 'POST' },
            reader: {   //这里的reader为数据存储组织的地方，下面的配置是为json格式的数据，例如：[{"total":50,"rows":[{"a":"3","b":"4"}]}]
                type: 'json', //返回数据类型为json格式
                root: 'rows',  //数据
                totalProperty: 'total' //数据总条数
            }
        },
        autoLoad: true  //即时加载数据
    });
	
	gridStorerp.on("beforeload",function(){
        Ext.apply(gridStorerp.proxy.extraParams,formrp.getForm().getValues());
        var projectId = Ext.getCmp("retainProjectStore").getValue();
        if(projectId == "-1"){
        	gridStorerp.proxy.extraParams.projectId = "";
        }
		var newResCode = resourcesCode;
		if(resourcesCode != "menu_0003_0001"){
			newResCode = resourcesCode + ",menu_0003_0001";
		}
        gridStorerp.proxy.extraParams.resourcesCode = newResCode;
    });
	
//	function onreload(){
//		gridStorerp.on("beforeload",function(){
//	        Ext.apply(gridStorerp.proxy.extraParams,formrp.getForm().getValues());
//	    });
//	}
	
	var gridrp = Ext.create('Ext.grid.Panel', {
		minHeight:600,
        store: gridStorerp,
        columnLines: true,
        columns: [{  
        	text : "操作",  
            dataIndex: 'actioncolumn',
            locked   : true,
            renderer: function(value,cellmeta,record,rowIndex,columnIndex,store) {
                var rec = gridrp.getStore().getAt(rowIndex);
                //查看
                return html = "<a href='"+jypath+"/marketing/retain/retainDetail?id="+rec.get('id')+"&returnUrl=,marketing,pin,index' style='cursor:pointer'>查看</a>"
                	//"<a href='"+jypath+"/marketing/retain/retainDetail?id="+rec.get('id')+"' style='cursor:pointer'>查看</a>"
            }
        },{
            text: '保留日期',
            dataIndex: 'retainDate',
            renderer:function(value){
            	return Ext.Date.format(new Date(value),'Y-m-d')
            }
        },{
            text     : '客户名称', 
            dataIndex: 'customerName'
        },{
            text     : '房号',
            dataIndex: 'combinedName',
            width:250,
            renderer: function(value,cellmeta,record,rowIndex,columnIndex,store) {
              	 var rec = gridrp.getStore().getAt(rowIndex);
                 	 var roomId = rec.get('roomId');
                 	 if(roomId!=null){
                 		 return "<a style='text-decoration:none;' href='javascript:openWindow("+roomId+")'>"+value+"</a>";
                 	 }
             	 return value;
             }
         
        },{
            text     : '户型',
            dataIndex: 'houseTypeName',
            renderer : function(val) {
                if (val == 0) {
                    return '正常';
                } else if (val == 1) {
                    return '已关闭';
                }
                return val;
            }
        },{
            text     : '房屋总价',
            dataIndex: 'totalPrice', renderer: Ext.util.Format.numberRenderer('0,000.00')
        },{
            text     : '保留有效开始日期',
            dataIndex: 'startValidity',
            width:150,
            renderer:function(value){
            	return Ext.Date.format(new Date(value),'Y-m-d')
            }
        },{
            text     : '保留有效结束日期',
            dataIndex: 'endValidity',
            width:150,
            renderer:function(value){
            	return Ext.Date.format(new Date(value),'Y-m-d')
            }
        },{
            text     : '经纪人',
            dataIndex: 'userName'
        },{
            text     : '业务状态',
            dataIndex: 'retainType',
            renderer : function(val) {
                if (val == 0) {
                    return '保留';
                } else if (val == 1) {
                    return '解除保留';
                }
                return val;
            }
        }],
        title: '保留列表',
        dockedItems: [{  
            xtype: 'pagingtoolbar',  
            store: gridStorerp,   // GridPanel中使用的数据  
            dock: 'bottom',  
            displayInfo: true,  
            emptyMsg:"没有数据",  
            displayMsg:"显示从{0}条数据到{1}条数据，共{2}条数据",
            id:'pagingToolb'
        }
        ]
    });
	
		
		var defaultConfirp = {
				defaults: {  
		            split: true,    //有分割线  
		            collapsible: true  //可以折叠
		        },
				items:[formrp,gridrp]
		};
		Ext.apply(this,defaultConfirp);
		this.callParent(arguments);
		
	}
});
